package com.wbp.cms.web.controller.admin;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
import com.wbp.cms.client.common.domain.DictionaryDO;
import com.wbp.cms.client.common.service.DictionaryService;
import com.wbp.cms.client.enums.ProductEnums;
import com.wbp.cms.client.product.domain.ProductDO;
import com.wbp.cms.client.product.domain.ProductProfitDO;
import com.wbp.cms.client.product.query.ProductQuery;
import com.wbp.cms.client.product.service.ProductService;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.util.DateUtils;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.web.controller.BaseController;
import com.wbp.cms.web.util.SessionUtil;


/**
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月12日 上午12:09:31 
 */
@Controller("productMgrController")
@RequestMapping("/productmgr")
public class ProductMgrController extends BaseController {

  private static final Logger  logger = Logger.getLogger(ProductMgrController.class) ;
  
   @Resource
   private ProductService productService ;
 
   @Resource
   private  DictionaryService  dictionaryService ;
   
   
   
   /**
    * 进入页面时的方法
    * @return
    */
   @RequestMapping("/tolist")
   public ModelAndView  toList(@RequestParam(value="type",required=true,defaultValue="0") Integer type){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/product/productList"); 
     
     queryProductDictionary(mv) ;
     
     mv.addObject("type", type) ;  // ==10:从预约项目中选择产品  
     
     return mv ;
   }

   
   /**
    * 查询产品的各种字典值,先从缓存中读取，再去查库
    * @param mv
    */
   private void queryProductDictionary(ModelAndView mv ){
     
     mv.addObject("isHotList", this.dictionaryService.queryDictionary("Product", "isHot") ) ;
     mv.addObject("tagList", this.dictionaryService.queryDictionary("Product", "tag") ) ;
     mv.addObject("profitTypeList", this.dictionaryService.queryDictionary("Product", "profitType") ) ;
     mv.addObject("productTypeList", this.dictionaryService.queryDictionary("Product", "productType") ) ;
     mv.addObject("investTypeList", this.dictionaryService.queryDictionary("Product", "investType") ) ;
     mv.addObject("investAreaList", this.dictionaryService.queryDictionary("Product", "investArea") ) ;
     mv.addObject("projectTermList", this.dictionaryService.queryDictionary("Product", "projectTerm") ) ;
     mv.addObject("paymentTypeList", this.dictionaryService.queryDictionary("Product", "paymentType") ) ;
     mv.addObject("profitPercentageList", this.dictionaryService.queryDictionary("Product", "profitPercentage") ) ; 
     mv.addObject("statusList", this.dictionaryService.queryDictionary("Product", "status") ) ;  
     mv.addObject("rateList", this.dictionaryService.queryDictionary("Product", "rate") ) ;  
     mv.addObject("bigSmallProportionList", this.dictionaryService.queryDictionary("Product", "bigSmallProportion") ) ;
   }
   
   /**
    * to 新增页面
    * @return
    */
   @RequestMapping("/toadd")
   public ModelAndView  toAddProduct(){
      ModelAndView mv = new ModelAndView();
      mv.setViewName("admin/product/productAdd"); 
      
      //加载各种字典值  
      queryProductDictionary(mv) ;
      
      String sequenceCode = UUID.randomUUID().toString();
      mv.addObject("sequenceCode", sequenceCode) ;  //产品序列号 不能修改
      mv.addObject("product_default_image_url", product_default_image_url) ; // default image
      return  mv ;
   }
   
   /**
    * 新增一条产品 
    * @return
    */
   @RequestMapping(value="/doadd", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public  String   doAddProduct(HttpServletRequest request  ){
     
     String params = this.getParameters(request).get("params") ; //  
     if(params == null  || params.equals(""))
         return JsonUtils.toJson(Result.buildError("参数不合法")) ;
     ProductDO productDO = JsonUtils.toObject(params, ProductDO.class) ;
     
     try{
       if(productDO == null )
         return JsonUtils.toJson(Result.buildError("参数不合法")) ;
       if(StringUtils.isEmpty(productDO.getName()))
         return JsonUtils.toJson(Result.buildError("产品名称不能为空")) ;
       
       UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
       if(user == null){
           return JsonUtils.toJson(Result.buildError("请重新登录")) ;
       }
       productDO.setCreator(user.getUserName()); 
       
       
       setProductProfitInfo(productDO) ;
       
       Result<Long> result = this.productService.addProduct(productDO) ;
       
       return  JsonUtils.toJson(Result.buildSuccess(result)) ;
       
     }catch(Throwable  t){
       logger.error(BaseResultCode.PRODUCT_ADD_PRODUCT_ERROR.getErrMsg(), t);
       return JsonUtils.toJson(Result.buildError(BaseResultCode.PRODUCT_ADD_PRODUCT_ERROR));
     }
     
    
   }
   
   /**
    * to 产品修改页面 
    * @param productId
    * @return
    */
   @RequestMapping("/toedit")
   public ModelAndView  toEditProduct(@RequestParam(value="productId",required=true,defaultValue="0") Long productId){
      ModelAndView mv = new ModelAndView();
      mv.setViewName("admin/product/productEdit"); 
      
      Result<ProductDO> result = this.productService.loadProduct(productId) ;
      if(result.isSuccess() && result.getData() !=null)
           mv.addObject("product",  result.getData()) ;
      
      //加载各种字典值  ，保存在本地缓存中  
      queryProductDictionary(mv) ;
      return  mv ;
   }
   
   
   /**
    * 编辑 产品 信息
    * @return
    */
   @RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doEditProduct(HttpServletRequest request /*@ModelAttribute ProductDO  productDO*/   ){
     try{
       
         String params = this.getParameters(request).get("params") ;  
         if(params == null  || params.equals(""))
             return JsonUtils.toJson(Result.buildError("参数不合法")) ;
         ProductDO  productDO = JsonUtils.toObject(params,ProductDO.class) ;
         if(productDO == null )
             return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        if(productDO.getId() == null || productDO.getId() <=0)
             return JsonUtils.toJson(Result.buildError("请重新刷新页面再修改产品信息")) ;
        
         // 判断productProfit是否存在 
         setProductProfitInfo(productDO) ;
        
         Result<Boolean>  result =this.productService.modifyProduct(productDO);
         
         return  JsonUtils.toJson(Result.buildSuccess(result),true) ;
     }catch(Throwable e){
       logger.error(BaseResultCode.PRODUCT_MODIFY_PRODUCT_ERROR.getErrMsg(), e);
       return JsonUtils.toJson(Result.buildError(BaseResultCode.PRODUCT_MODIFY_PRODUCT_ERROR));
     }
   }
   
   private void  setProductProfitInfo(ProductDO  productDO){
     if(productDO.getProductProfits()!=null){
       List<ProductProfitDO> productProfitList= JsonUtils.toObjectArray(productDO.getProductProfits(),  ProductProfitDO.class) ;
       if(productProfitList!=null && productProfitList.size()  > 0){
         productDO.setProductProfitList(productProfitList);
       }
    }
   }
   
   /**
    * 查询
    * @param name
    * @param isHot
    * @param tag
    * @param productType
    * @param paymentType
    * @param pageNo
    * @param pageSize
    * @return
    */
   @RequestMapping(value="/query", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String doQuery(HttpServletRequest request,@RequestParam(value = "name",
       required = false, defaultValue = "") String name, @RequestParam(value = "isHot",
       required = false, defaultValue = "-1") int isHot,@RequestParam(value = "tag",
       required = false, defaultValue = "0") int tag,@RequestParam(value = "productType",
       required = false, defaultValue = "0") int productType ,@RequestParam(value = "paymentType",
       required = false, defaultValue = "0") int paymentType ,@RequestParam(value = "investType",
       required = false, defaultValue = "0") int investType ,@RequestParam(value = "status", 
       required = false, defaultValue = "0") int status ,@RequestParam(value = "detailAddress", 
           required = false, defaultValue = "") String detailAddress , @RequestParam(value = "start",
       required = false, defaultValue = "1") int start,@RequestParam(value = "length",
       required = false, defaultValue = "50") int pageSize) {
     
     Map<String,String> maps = this.getParameters(request) ;
     
     ProductQuery  productQuery =new ProductQuery();
     // productQuery.setPageNo(pageNo);
     productQuery.setStart(start);
     productQuery.setPageSize(pageSize);
     if(StringUtils.isNotEmpty(name))
        productQuery.setName(name);
  
     productQuery.setIsHot(isHot);
    // if(tag > 0)
    productQuery.setTag(tag) ; 
    // if(productType > 0)
    productQuery.setProductType(productType);
    // if(paymentType > 0)
    productQuery.setPaymentType(paymentType);
    productQuery.setInvestType(investType);
    productQuery.setStatus(status);
    productQuery.setDetailAddress(detailAddress);
     
     Result<List<ProductDO>> result = this.productService.queryProduct(productQuery) ;
 
     if(result.isSuccess() && result.getData()!=null && !result.getData().isEmpty() ){
         for(ProductDO pd : result.getData()){
              pd.setProductTypeDesc( getDictionaryDesc("Product", "productType",  pd.getProductType()) ) ;
              pd.setIsHotDesc( getDictionaryDesc("Product", "isHot",  pd.getIsHot()) ) ; 
              pd.setProfitTypeDesc( getDictionaryDesc("Product", "profitType",  pd.getProfitType()) ) ; 
              pd.setInvestTypeDesc( getDictionaryDesc("Product", "investType",  pd.getInvestType()) ) ;
              pd.setTagDesc( getDictionaryDesc("Product", "tag",  pd.getTag()) ) ; 
              pd.setPaymentTypeDesc( getDictionaryDesc("Product", "paymentType",  pd.getPaymentType()) ) ; 
              pd.setStatusDesc( getDictionaryDesc("Product", "status",  pd.getStatus()) ) ; 
              if(pd.getCreateTime() !=null)
                 pd.setCreateTimeDesc(DateUtils.format(pd.getCreateTime(), DateUtils.ISO_DATE_FORMAT));
              if(pd.getUpdateTime() != null)
                 pd.setUpdateTimeDesc(DateUtils.format(pd.getUpdateTime(), DateUtils.ISO_DATE_FORMAT));
         }
     }
     return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
      
   } 
   
   /**
    * 取字典值的描述显示在产品页面上
    * @param tableName
    * @param attributeName
    * @param value
    * @return
    */
   private String  getDictionaryDesc(String tableName,String attributeName, int value){
     DictionaryDO  dictionary = this.dictionaryService.queryDictionary(tableName, attributeName,  value ) ;
     if(dictionary == null || dictionary.getDescription()==null)
        return "" ;
     return dictionary.getDescription() ;
   }
   
   /*@RequestMapping(value="/query", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String doQuery(@ModelAttribute  ProductQuery  productQuery ) {
     Result<List<ProductDO>> result = this.productService.queryProduct(productQuery) ;
     return new Gson().toJson(Result.buildSuccess(result)) ;
   }*/
   
   /**
    * 上下架
    * @param productId
    * @return
    */
   @RequestMapping("/upordown")
   @ResponseBody
   public String  doUpOrDown(@RequestParam(value="productId",required=true,defaultValue="0") Long productId ){
       Result<ProductDO> result = this.productService.loadProduct(productId) ;
       if(result.isFailed()){
          return new Gson().toJson(Result.buildError("productId:"+productId+",没有找到此产品,请刷新列表"));
       }
       try{
         
         ProductDO  p = result.getData() ;
         if(p.getStatus() ==ProductEnums.Product_Status_Enums.Starting.getValue() ){  // 上架中，
             p.setStatus(ProductEnums.Product_Status_Enums.Down.getValue());
         }else if(p.getStatus() ==ProductEnums.Product_Status_Enums.Down.getValue()){  // 下架
              p.setStatus(ProductEnums.Product_Status_Enums.Starting.getValue());
         }
         Result<Boolean> r = this.productService.updateProduct(p) ;
         if(r.isFailed())
            return new Gson().toJson(Result.buildError("productId:"+productId+",修改失败"));
         
         return  new Gson().toJson(Result.buildSuccess(true) )  ;
       }catch(Throwable e){
         logger.error("error productId:"+productId,e);
         return new Gson().toJson(Result.buildError("productId:"+productId+",修改失败"));
       }
   }
   
   
   
   
}
